package com.bm.web.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bm.service.ImgService;
import com.bm.service.impl.ImgServiceImpl;

/**
 * Servlet implementation class adminWordServlet
 */
@WebServlet("/adminWordServlet")
public class adminWordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public adminWordServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		
        // 设置响应内容类型为图片
        response.setContentType("image");
        
        // 生成验证码字符串
        String captchaStr = generateRandomString();
        // 将验证码字符串保存到Session中
        HttpSession session = request.getSession();
        session.setAttribute("captcha", captchaStr);
        
        // 生成验证码图像
        BufferedImage image = generateCaptchaImage(captchaStr);
        
        // 将图像输出到响应流中

        OutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "png", outputStream);
        outputStream.close();
        
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		 // 获取用户输入的验证码
        String userInputCaptcha = request.getParameter("captcha");
		ImgService imgservice = new ImgServiceImpl();
		
		String userName = request.getParameter("aboutNewBox2BoxMessage1");
		String userPhone = request.getParameter("aboutNewBox2BoxMessage2");
		String userWord = request.getParameter("aboutNewBox2BoxMessage3");
        // 获取Session中存储的验证码
        HttpSession session = request.getSession();
        String generatedCaptcha = (String) session.getAttribute("captcha");
        
        // 比较用户输入的验证码和生成的验证码
        if (generatedCaptcha != null && generatedCaptcha.equals(userInputCaptcha)) {
            // 验证码正确
        	session.setAttribute("xx", -1);
        	imgservice.userWord(userName, userPhone, userWord);
    		request.getRequestDispatcher("cocoOur.jsp").forward(request, response);
        } else {
            // 验证码错误
        	session.setAttribute("xx", 1);
        	request.getRequestDispatcher("cocoOur.jsp").forward(request, response);
            response.getWriter().println("验证码错误，请重新输入");
        }
	}
	
	  private String generateRandomString() {
	        int length = 4; // 验证码长度
	        String charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	        Random random = new Random();
	        StringBuilder sb = new StringBuilder();
	        for (int i = 0; i < length; i++) {
	            int index = random.nextInt(charset.length());
	            sb.append(charset.charAt(index));
	        }
	        return sb.toString();
	    }
	    
	    // 生成验证码图像
	    private BufferedImage generateCaptchaImage(String captchaStr) {
	        int width = 150;
	        int height = 50;
	        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	        Graphics2D graphics = image.createGraphics();
	        
	        // 设置背景色
	        graphics.setColor(Color.WHITE);
	        graphics.fillRect(0, 0, width, height);
	        
	        // 设置字体和颜色
	        graphics.setFont(new Font("Arial", Font.BOLD, 24));
	        graphics.setColor(Color.BLACK);
	        
	        // 绘制验证码字符串
	        graphics.drawString(captchaStr, 10, 30);
	        
	        
	        graphics.dispose();
	        return image;
	    }

}
